package com.dhcc.DRGsHosp.facade.impl;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Named;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openkoala.koala.commons.InvokeResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import com.dhcc.DRGsHosp.application.AnnualSTDApplication;
import com.dhcc.DRGsHosp.application.QuotaApplication;
import com.dhcc.DRGsHosp.application.QuotaManageApplication;
import com.dhcc.DRGsHosp.core.domain.AnnualSTD;
import com.dhcc.DRGsHosp.core.domain.ManageSummary;
import com.dhcc.DRGsHosp.facade.BenchmarkFileUploadFacade;
import com.dhcc.DRGsHosp.facade.DepartmentFacade;
import com.dhcc.DRGsHosp.infra.util.ExcelUtil;
import com.dhcc.DRGsHosp.infra.util.MonitorResultUtil;

/**
 * @title		:FileUploadFacadeImpl.java
 * @description	:
 * @author		:chenhanlin
 * @date		:2017年06月15日
 * @version     :1.0
 * @copyright   :DHCC 2016-2017 
 */
@Scope("session")
@Named("drgsHospFacadeImplchl20170615")
public class BenchmarkFileUploadFacadeImpl implements BenchmarkFileUploadFacade,Serializable {
	private static final long serialVersionUID = -1474745132287740189L;
	private static Logger logger = LoggerFactory.getLogger(BenchmarkFileUploadFacadeImpl.class);
	@Autowired
	private QuotaManageApplication  quotaManageApplication;
	
	@Autowired
	private AnnualSTDApplication annualSTDApplication;
	
	
	@Autowired
	private QuotaApplication quotaApplication;
	
	
	@Autowired
	private DepartmentFacade departmentFacade ;
	
	private StringBuffer message = new StringBuffer() ;//返回前台的信息
	
	private Float percent = new Float(0);//进度完成百分比
	
	private String detail="";//进度进行详情
	
	private String time="";
	
	private long mdStartTime=0;
	
	private String stateInfo="";//状态信息 error-错误  done-完成一个  finish-结束
	
	private int all = 1;//总数
	private int cur = 0;//当前数
	

	/**
	 * 
	 *  @Description：外部标杆导入
	 *  @Author LiuHongJun  
	 *  @see com.dhcc.DRGsHosp.facade.BenchmarkFileUploadFacade#importExternalBenchmarkData(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public  InvokeResult importExternalBenchmarkData(String filePath, String role, String parMscode) {
		//获取指标表 代码与描述的映射关系
		List<Map<String,Object>> quotaList = quotaApplication.getQuotaList("");
		Map<String,Object> quotaMap = new HashMap<String,Object>();
		for(int i = 0; i<quotaList.size();i++){
			quotaMap.put(quotaList.get(i).get("TEXT").toString(),quotaList.get(i).get("QUOTA_CODE"));
		}
		//判断 表头中的指标是否都能在 指标映射关系中找到
		detail="";
		message = new StringBuffer("") ;
		if( parMscode == null ) {
			message.append( "管理目标编码为空，保存失败") ;
			InvokeResult.failure("管理目标编码为空，保存失败") ;
		}
		
		try {
	        percent = 0F ;
	        stateInfo = "0" ;
			message.append("准备解析 ，请稍等！<br>") ;
			percent=0f;//进度完成百分比
			stateInfo="";//状态信息 error-错误  done-完成一个  finish-结束
			Row row = null ;
			// 管理目标数据表
			Sheet sheetBenchmark = readExcelSheet(filePath,0,"") ;
			Row titleRow = sheetBenchmark.getRow(0);
			int rowNumBenchmark=sheetBenchmark.getLastRowNum();
			int colNumBenchmark=titleRow.getLastCellNum();
			Map<Integer,Object> positionMap = new HashMap<Integer,Object>();
			String illegalTitle = "指标:";
			for(int i = 2;i<colNumBenchmark;i++){
				String title = titleRow.getCell(i).getStringCellValue();
				if(quotaMap.containsKey(title)){
					positionMap.put(i,title);
				}else{//当前指标描述不在指标表中给出提示
					illegalTitle += title +" ";
				}
			}
			if(!"指标:".equals(illegalTitle)){
				illegalTitle += "描述不准确或者系统暂时不支持相关指标,请参照上传模版中的说明进行修改。";
				stateInfo = "1" ;
				message.append(illegalTitle) ;
				return InvokeResult.failure("") ;
			}
			// 保存管理目标信息
			ManageSummary manageSummary = new ManageSummary() ;
			manageSummary.setMsCode( parMscode );
			
			// 内置标杆默认存0(不可用)，其他存1(可用)
			if( parMscode.endsWith("inner") ) {
				manageSummary.setMsFlag("0");
			} else {
				manageSummary.setMsFlag("1");
			}
			try {
				quotaManageApplication.saveManageSummary(manageSummary) ;
			} catch (Exception e) {
				e.printStackTrace();
				message.append( "保存管理目标时报错，请检查 <br>") ;
				logger.error(e.getMessage());
				InvokeResult.failure(e.getMessage()) ;
			}
			
			message.setLength(0);
			message.append("正在解析文件    "+filePath.substring(filePath.lastIndexOf("\\")+1) + "<br>") ;
			long startTime=new Date().getTime();
			mdStartTime = startTime;
			// 解析并保存管理目标数据表
			for (int i = 1; i <= rowNumBenchmark; i++) {
				percent=(float)i*100/(float)rowNumBenchmark;
				printProgress(rowNumBenchmark,i) ;
				row=sheetBenchmark.getRow(i);
				// 该行为空时解析下一行
				if(null == row) {
					message.append("第" + (i+1) +"行数据为空，跳过<br> ")   ;
					continue ;
				}
				for(int j=2;j<colNumBenchmark;j++){
					try {
						String yaer=ExcelUtil.getCellValue(row.getCell(0));
						String  drgCode=ExcelUtil.getCellValue(row.getCell(1));
						String quotaCode=positionMap.get(j)==null?null:(quotaMap.get(positionMap.get(j))==null?null:quotaMap.get(positionMap.get(j)).toString());
						double bvalue=MonitorResultUtil.objectToDouble(ExcelUtil.getCellValue(row.getCell(j)));
						quotaManageApplication.saveOutStd(yaer,quotaCode,drgCode,parMscode,bvalue);
					} catch (Exception e) {
						e.printStackTrace();
						message.append( "保存第" + (i+1) +"行数据时报错，请检查<br> ") ;
						logger.error(e.getMessage());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ExcelUtil.deleteFile(filePath);
		}
		stateInfo = "1" ;
		percent = 100f ;
		return InvokeResult.success() ;
	}
/**
 * 
 *  @Description：计算标杆导入
 *  @Author LiuHongJun  
 *  @see com.dhcc.DRGsHosp.facade.BenchmarkFileUploadFacade#importCalculateBenchmark(java.lang.String)
 */
	@Override
	public InvokeResult importCalculateBenchmark (String filePath,String drgVersion,String calculateType) {
		try {
			message = new StringBuffer("") ;
			detail="";
	        percent = 0F ;
	        stateInfo = "0" ;
			message.append("准备解析 ，请稍等！<br>") ;
			Row row = null ;
	 		Sheet sheet = readExcelSheet(filePath,0,"") ;
			int rowNum=sheet.getLastRowNum();//行数
			message.setLength(0);
			message.append("正在解析文件    "+filePath.substring(filePath.lastIndexOf("\\")+1) + "<br>");
			for (int i = 1; i <= rowNum; i++) {
				cur = i+1 ;
				row=sheet.getRow(i);
				// 该行为空时解析下一行
				if(null == row) {
					message.append( "第" + (i+1) +"行数据为空，跳过<br> ") ;
					continue ;
				}
				AnnualSTD annualSTD = new AnnualSTD() ;
				percent=(float)i*100/(float)rowNum;
				printProgress(rowNum,i) ;
				for (int j = 0; j <= 16 ; j++) {
					String value = ExcelUtil.getCellValue(row.getCell(j)) ;
					if(StringUtils.isBlank(value) && (j==0||j==1) ) {
						continue ;
					}
					switch(j) {
						// 标杆年份
						case 0 :  annualSTD.setAsYear(value) ; break ;
						// DRG 代码
						case 1 : {
							 		annualSTD.setAsDrgCode(value);
							 		annualSTD.setAsMdcCode("MDC" + value.substring(0, 1)) ;
								 } 
									break ;
						// 入组病例数
						case 2 :  annualSTD.setAsTotalCase(MonitorResultUtil.objectToDouble(value)) ; break ;
						// 平均住院日
						case 3 :  annualSTD.setAsAvgDays(MonitorResultUtil.round(value, 2)) ; break ;
						// 次均费用
						case 4 :  annualSTD.setAsAvgFee(MonitorResultUtil.round(value, 2)) ;
						          annualSTD.setPrimevalAvgFee(MonitorResultUtil.round(value, 2)); break ;
						// 权重
						case 5 :  annualSTD.setAsWeight(MonitorResultUtil.round(value, 2)); break ;
						// 死亡病例数
						case 6 :  annualSTD.setAsDeadCnt(MonitorResultUtil.objectToDouble(value)); break ;
						// 死亡风险等级
						case 7 :  annualSTD.setAsRiskLevel(MonitorResultUtil.objectToDouble(value)); break ;
						// 医疗费标杆
						case 8 :  annualSTD.setAsDrgMedCost(MonitorResultUtil.round(value, 2)); break ;
						// 护理费标杆
						case 9 :  annualSTD.setAsDrgNursCost(MonitorResultUtil.round(value, 2)); break ;
						// 医技费标杆
						case 10 :  annualSTD.setAsDrgTechCost(MonitorResultUtil.round(value, 2)); break ;
						// 药耗费标杆
						case 11 :  annualSTD.setAsDrgDrugCost(MonitorResultUtil.round(value, 2)); break ;
						// 管理费标杆
						case 12 :  annualSTD.setAsDrgManageCost(MonitorResultUtil.round(value, 2)); break ;
						// 药占比
						case 13 :  annualSTD.setAsDrugRatio(MonitorResultUtil.objectToDouble(value)); break ;
						// 次均药费
						case 14 : annualSTD.setAsAvgDrugFee(MonitorResultUtil.round(value, 2)); break ;
						// 次均耗材费
						case 15 : annualSTD.setAsAvgMaterialFee(MonitorResultUtil.round(value, 2)); break ;
						// 死亡率
						case 16 : 
							annualSTD.setAsDiedRatio(MonitorResultUtil.round(value, 2)); 
							break ;
					}
				}
				//如果次均费用不为0，则 耗材占比 = 次均耗材费 / 次均费用
				if( annualSTD.getAsAvgFee() != 0 ){
					annualSTD.setAsMaterialRatio( MonitorResultUtil.round( (annualSTD.getAsAvgMaterialFee() / annualSTD.getAsAvgFee()) *100+"",2) );
				}else{
					annualSTD.setAsMaterialRatio(MonitorResultUtil.round("0", 2));
				}
				annualSTD.setVerCode(drgVersion);
				annualSTD.setAsStdType(calculateType);
				annualSTD.setAsId(drgVersion+"_"+calculateType+"_"+annualSTD.getAsYear());
				annualSTD.setAsPid(annualSTD.getAsId()+"-"+annualSTD.getAsDrgCode());
				detail=drgVersion+"_"+calculateType+"_"+annualSTD.getAsYear()+"_"+annualSTD.getAsDrgCode();
				try {
					annualSTDApplication.creatAnnualSTD(annualSTD);
				} catch (Exception e) {
					message.append("保存第" + (i+1) +"行数据时报错，请检查<br> ")  ;
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ExcelUtil.deleteFile(filePath) ;
		}
		stateInfo = "1" ;
		percent = 100f ;
		return InvokeResult.success() ;
	}
	
	/**
	 * 
	 *  @Description：绩效标杆导入
	 *  @Author LiuHongJun  
	 *  @see com.dhcc.DRGsHosp.facade.BenchmarkFileUploadFacade#importPerformanceBenchmark(java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public InvokeResult importPerformanceBenchmark(String filePath,String role,String parMscode) {
		detail="";
		message = new StringBuffer("") ;
		if( parMscode == null ) {
			message.append( "管理目标编码为空，保存失败") ;
			return InvokeResult.failure("") ;
		}
		//获取指标表 代码与描述的映射关系
		List<Map<String,Object>> quotaList = quotaApplication.getQuotaList("");
		Map<String,Object> quotaMap = new HashMap<String,Object>();
		for(int i = 0; i<quotaList.size();i++){
			quotaMap.put(quotaList.get(i).get("TEXT").toString(),quotaList.get(i).get("QUOTA_CODE"));
		}
		Sheet sheet = null ;
 		Row row = null ;
 		Row titleRow = null;
 		int rowNum = 0;
		int colNum = 0;
		//检查一下title
		String illegalInfo = "";
		if ("manager_inner".equals(parMscode)) {
			//manager_inner--管理目标值
			String[] sheetNames = {"全院标杆","科室组标杆","科室标杆","全院病组标杆","科室病组标杆"};
			for(String sheetName:sheetNames){
				sheet = readExcelSheet(filePath,0,sheetName);
				if(sheet!=null) {
					row = sheet.getRow(0);
					colNum = row.getLastCellNum();
				}
				String illegalTitle = "指标:";
				for(int i = 0;i<colNum;i++){
					String title = row.getCell(i).getStringCellValue();
					if(!quotaMap.containsKey(title)&&!"标杆年份科室组名称科室名称DRG编码".contains(title)){//当前指标描述不在指标表中给出提示
						illegalTitle += title +" ";
					}
				}
				if(!"指标:".equals(illegalTitle)){
					illegalInfo +=illegalInfo+sheetName+" "+illegalTitle+"<br/>";
				}
			}
		} else {
			sheet = readExcelSheet(filePath,0,"");
			if(sheet!=null) {
				row = sheet.getRow(0);
				colNum = row.getLastCellNum();
			}
			String illegalTitle = "指标:";
			for(int i = 0;i<colNum;i++){
				String title = row.getCell(i).getStringCellValue();
				if(!quotaMap.containsKey(title)&&!"标杆年份科室组名称科室名称DRG编码".contains(title)){//当前指标描述不在指标表中给出提示
					illegalTitle += title +" ";
				}
			}
			if(!"指标:".equals(illegalTitle)){
				illegalInfo += illegalTitle+"<br/>";
			}
		}

		if(!"".equals(illegalInfo)){
			illegalInfo += "描述不准确或者系统暂时不支持相关指标,请参照上传模版中的说明进行修改。";
			message.append(illegalInfo) ;
			stateInfo  = "1" ;
			return InvokeResult.failure(illegalInfo) ;
		}
		// 保存管理目标信息
		ManageSummary manageSummary = new ManageSummary() ;
		manageSummary.setMsCode( parMscode );
		// 内置标杆默认存0(不可用)，其他存1(可用)
		if( parMscode.endsWith("inner") ) {
			manageSummary.setMsFlag("0");
		} else {
			manageSummary.setMsFlag("1");
		}
		try {
			quotaManageApplication.saveManageSummary(manageSummary) ;
		} catch (Exception e) {
			e.printStackTrace();
			message.append( "保存管理目标时报错，请检查 <br>") ;
			logger.error(e.getMessage());
			return InvokeResult.failure(e.getMessage()) ;
		}
		percent = 0F ;
        stateInfo = "0" ;
		message.append("准备解析 ，请稍等！<br>") ;
		try {
			if ("manager_inner".equals(parMscode)) {// manager_inner--管理目标值
				List<Map<String,Object>> depRelatedInfo = departmentFacade.findAllDepRelatedInfo() ;
				Map<String,String> depMap = new HashMap<>() ;
				Map<String,String> depGroupMap = new HashMap<>() ;
				for(Map<String,Object> map : depRelatedInfo) {
					String depCode = map.get("DEPCODE") == null ? "" : map.get("DEPCODE").toString() ;
					String depName = map.get("DEPNAME") == null ? "" : map.get("DEPNAME").toString() ;
					depMap.put(depName,depCode) ; 
					String depgroupcode = map.get("DEPGROUPCODE") == null ? "" : map.get("DEPGROUPCODE").toString() ;
					String depgroupdesc = map.get("DEPGROUPDESC") == null ? "" : map.get("DEPGROUPDESC").toString() ;
					depMap.put(depName,depCode) ; 
					depGroupMap.put(depgroupdesc,depgroupcode) ; 
				}
				//获取全院标杆
				sheet = readExcelSheet(filePath,0,"全院标杆");
				if(sheet!=null){//保存全院指标
					rowNum=sheet.getLastRowNum();//行数
					titleRow = sheet.getRow(0);
					colNum = titleRow.getLastCellNum();
					Map<Integer,Object> positionMap = new HashMap<Integer,Object>();
					for(int i = 1;i<colNum;i++){
						String title = titleRow.getCell(i).getStringCellValue();
						if(quotaMap.containsKey(title)){
							positionMap.put(i,title);
						}
					}
					// 解析并保存管理目标数据表
					for (int i = 1; i <= rowNum; i++) {
						row=sheet.getRow(i);
						// 该行为空时解析下一行
						if(null == row) {
							message.append("第" + (i+1) +"行数据为空，跳过<br> ")   ;
							continue ;
						}
						for(int j=1;j<colNum;j++){
							try {
								String quotaCode=positionMap.get(j)==null?null:(quotaMap.get(positionMap.get(j))==null?null:quotaMap.get(positionMap.get(j)).toString());
								String year=ExcelUtil.getCellValue(row.getCell(0));
								double value=MonitorResultUtil.objectToDouble(ExcelUtil.getCellValue(row.getCell(j)));
								quotaManageApplication.saveHospManager(parMscode,year,quotaCode,value);					
								detail="全院标杆-"+positionMap.get(j)==null?"":positionMap.get(j)+"";
							}catch(Exception e) {
								message.append("更新第" + (i+1) +"行数据时报错，请检查<br> ")  ;
								logger.error(e.getMessage()+"更新第\" + (i+1) +\"行数据时报错，请检查<br>");
							}
						}
					}
				}
				printProgress(5,1);
				//获取科室组标杆
				sheet = readExcelSheet(filePath,0,"科室组标杆");
				if(sheet!=null){//保存科室组标杆
					titleRow = sheet.getRow(0);
					rowNum=sheet.getLastRowNum();//行数
					colNum = titleRow.getLastCellNum();
					Map<Integer,Object> positionMap = new HashMap<Integer,Object>();
					for(int i = 2;i<colNum;i++){
						String title = titleRow.getCell(i).getStringCellValue();
						if(quotaMap.containsKey(title)){
							positionMap.put(i,title);
						}
					}
					// 解析并保存管理目标数据表
					for (int i = 1; i <= rowNum; i++) {
						row=sheet.getRow(i);
						// 该行为空时解析下一行
						if(null == row) {
							message.append("第" + (i+1) +"行数据为空，跳过<br> ")   ;
							continue ;
						}
						for(int j=2;j<colNum;j++){
							try {
								String depGroupName = ExcelUtil.getCellValue(row.getCell(1)) ;
								String depGroupCode = depGroupMap.get(depGroupName) ;
								// 名称不为空而编码为空，则名称无效
								if(StringUtils.isBlank(depGroupCode)) {
									message.append("第" + (i+1) +"行科室组名称无效，请检查<br> ")  ;
									continue ;
								}
								String quotaCode=positionMap.get(j)==null?null:(quotaMap.get(positionMap.get(j))==null?null:quotaMap.get(positionMap.get(j)).toString());
								double value =MonitorResultUtil.objectToDouble(ExcelUtil.getCellValue(row.getCell(j)));
								String year=ExcelUtil.getCellValue(row.getCell(0));
								quotaManageApplication.saveDepGroupManager(depGroupCode,parMscode,year,quotaCode,value);
								detail="科室组标杆-"+depGroupName+"-"+positionMap.get(j)+"";
							} catch (Exception e) {
								message.append("更新第" + (i+1) +"行数据时报错，请检查<br> ")  ;
								logger.error(e.getMessage()+"更新第\" + (i+1) +\"行数据时报错，请检查<br>");
							}
						}
					}
				}
				printProgress(5,2);
				//获取科室标杆
				sheet = readExcelSheet(filePath,0,"科室标杆");
				if(sheet!=null){//保存科室标杆
					titleRow = sheet.getRow(0);
					rowNum=sheet.getLastRowNum();//行数
					colNum = titleRow.getLastCellNum();
					Map<Integer,Object> positionMap = new HashMap<Integer,Object>();
					for(int i = 2;i<colNum;i++){
						String title = titleRow.getCell(i).getStringCellValue();
						if(quotaMap.containsKey(title)){
							positionMap.put(i,title);
						}
					}
					// 解析并保存管理目标数据表
					for (int i = 1; i <= rowNum; i++) {
						row=sheet.getRow(i);
						// 该行为空时解析下一行
						if(null == row) {
							message.append("第" + (i+1) +"行数据为空，跳过<br> ")   ;
							continue ;
						}
						for(int j=2;j<colNum;j++){
							try {
								String depName = ExcelUtil.getCellValue(row.getCell(1)) ;
								String depCode = depMap.get(depName) ;
								// 名称不为空而编码为空，则名称无效
								if(StringUtils.isBlank(depCode) ) {
									message.append("第" + (i+1) +"行科室名称无效，请检查<br> ")  ;
									continue ;
								}
								String quotaCode=positionMap.get(j)==null?null:(quotaMap.get(positionMap.get(j))==null?null:quotaMap.get(positionMap.get(j)).toString());
								double value =MonitorResultUtil.objectToDouble(ExcelUtil.getCellValue(row.getCell(j)));
								String year=ExcelUtil.getCellValue(row.getCell(0));
								quotaManageApplication.saveDepManager(depCode,parMscode,year,quotaCode,value);
								detail="科室标杆-"+depName+"-"+positionMap.get(j)+"";
							} catch (Exception e) {
								e.printStackTrace();
								message.append("更新第" + (i+1) +"行数据时报错，请检查<br> ");
								logger.error(e.getMessage()+"更新第\" + (i+1) +\"行数据时报错，请检查<br>");
							}
						}
					}
				}
				printProgress(5,3);
				//获取全院病组标杆
				sheet = readExcelSheet(filePath,0,"全院病组标杆");
				if(sheet!=null){//保存全院病组标杆
					titleRow = sheet.getRow(0);
					rowNum=sheet.getLastRowNum();//行数
					colNum = titleRow.getLastCellNum();
					Map<Integer,Object> positionMap = new HashMap<Integer,Object>();
					for(int i = 2;i<colNum;i++){
						String title = titleRow.getCell(i).getStringCellValue();
						if(quotaMap.containsKey(title)){
							positionMap.put(i,title);
						}
					}
					// 解析并保存管理目标数据表
					for (int i = 1; i <= rowNum; i++) {
						row=sheet.getRow(i);
						// 该行为空时解析下一行
						if(null == row) {
							message.append("第" + (i+1) +"行数据为空，跳过<br> ")   ;
							continue ;
						}
						for(int j=2;j<colNum;j++){
							try {
								String drgCode =ExcelUtil.getCellValue(row.getCell(1)) ;
								if(StringUtils.isBlank(drgCode)) {
									message.append("第" + (i+1) +"行病组代码无效，请检查<br> ")  ;
									continue ;
								}
								String quotaCode=positionMap.get(j)==null?null:(quotaMap.get(positionMap.get(j))==null?null:quotaMap.get(positionMap.get(j)).toString());
								double value =MonitorResultUtil.objectToDouble(ExcelUtil.getCellValue(row.getCell(j)));
								String year=ExcelUtil.getCellValue(row.getCell(0));
								quotaManageApplication.saveDrgManager(drgCode,parMscode,year,quotaCode,value);
								detail="全院病组标杆-"+ExcelUtil.getCellValue(row.getCell(1))+"-"+positionMap.get(j)+"";
							} catch (Exception e) {
								e.printStackTrace();
								message.append("更新第" + (i+1) +"行数据时报错，请检查<br> ");
								logger.error(e.getMessage()+"更新第\" + (i+1) +\"行数据时报错，请检查<br>");
							}						
						}
					}
				}
				printProgress(5,4);
				//获取科室病组标杆
				sheet = readExcelSheet(filePath,0,"科室病组标杆");
				if(sheet!=null){//保存科室病组标杆
					titleRow = sheet.getRow(0);
					rowNum=sheet.getLastRowNum();//行数
					colNum = titleRow.getLastCellNum();
					Map<Integer,Object> positionMap = new HashMap<Integer,Object>();
					for(int i = 3;i<colNum;i++){
						String title = titleRow.getCell(i).getStringCellValue();
						if(quotaMap.containsKey(title)){
							positionMap.put(i,title);
						}
					}
					// 解析并保存管理目标数据表
					for (int i = 1; i <= rowNum; i++) {
						row=sheet.getRow(i);
						// 该行为空时解析下一行
						if(null == row) {
							message.append("第" + (i+1) +"行数据为空，跳过<br> ")   ;
							continue ;
						}
						for(int j=3;j<colNum;j++){
							try {
								String depName = ExcelUtil.getCellValue(row.getCell(1)) ;
								String depCode = depMap.get(depName) ;
								String drgCode =ExcelUtil.getCellValue(row.getCell(2)) ;
								// 名称不为空而编码为空，则名称无效
								if(StringUtils.isBlank(depCode) ) {
									message.append("第" + (i+1) +"行科室名或DRG病组代码称无效，请检查<br> ")  ;
									continue ;
								}
								String quotaCode=positionMap.get(j)==null?null:(quotaMap.get(positionMap.get(j))==null?null:quotaMap.get(positionMap.get(j)).toString());
								double value =MonitorResultUtil.objectToDouble(ExcelUtil.getCellValue(row.getCell(j)));
								String year=ExcelUtil.getCellValue(row.getCell(0));
								quotaManageApplication.saveDepDrgManager(drgCode,depCode,parMscode,year,quotaCode,value);
								detail="科室病组标杆-"+ExcelUtil.getCellValue(row.getCell(1))+"-"+ExcelUtil.getCellValue(row.getCell(2))+"-"+positionMap.get(j)+"";
							} catch (Exception e) {
								e.printStackTrace();
								message.append("更新第" + (i+1) +"行数据时报错，请检查<br> ");
								logger.error(e.getMessage()+"更新第\" + (i+1) +\"行数据时报错，请检查<br>");
							}	
						}
					}
				}
				printProgress(5,5);
			}else{  //其他绩效标杆值,管理目标数据表
					sheet = readExcelSheet(filePath,0,"") ;
					if(sheet!=null) {
						titleRow = sheet.getRow(0);
						rowNum = sheet.getLastRowNum();
						colNum=titleRow.getLastCellNum();
					}
					Map<Integer,Object> positionMap = new HashMap<Integer,Object>();
					for(int i = 1;i<colNum;i++){
						String title = titleRow.getCell(i).getStringCellValue();
						if(quotaMap.containsKey(title)){
							positionMap.put(i,title);
						}
					}
					// 解析并保存管理目标数据表
					for (int i = 1; i <= rowNum; i++) {
						printProgress(rowNum,i);
						row=sheet.getRow(i);
						// 该行为空时解析下一行
						if(null == row) {
							message.append("第" + (i+1) +"行数据为空，跳过<br> ")   ;
							continue ;
						}
						for(int j=1;j<colNum;j++){
							try {
								String quotaCode=positionMap.get(j)==null?null:(quotaMap.get(positionMap.get(j))==null?null:quotaMap.get(positionMap.get(j)).toString());
								double value =MonitorResultUtil.objectToDouble(ExcelUtil.getCellValue(row.getCell(j)));
								String year=ExcelUtil.getCellValue(row.getCell(0));
								quotaManageApplication.saveOtherManager(parMscode,year,quotaCode,value);
								detail="全院其他机构标杆-"+ExcelUtil.getCellValue(row.getCell(1))+"-"+positionMap.get(j)+"";
							} catch (Exception e) {
								e.printStackTrace();
								message.append("更新第" + (i+1) +"行数据时报错，请检查<br> ");
								logger.error(e.getMessage()+"更新第\" + (i+1) +\"行数据时报错，请检查<br>");
							}	
							detail="全院其他机构-"+ExcelUtil.getCellValue(row.getCell(1))+"-"+positionMap.get(j)+"";
						}
					}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ExcelUtil.deleteFile(filePath) ;
		}
		stateInfo = "1" ;
		percent = 100f ;
		return InvokeResult.success() ;
	}
	
	
	/**读取Excel 工作簿
	 * 
	 * @param filePath
	 * @param index
	 * @return
	 */
	private Sheet readExcelSheet(String filePath,int index,String sheetName) {
		String extension=filePath.substring(filePath.lastIndexOf(".")).toLowerCase();//扩展名
		Workbook workbook=null;
		Sheet sheet=null;
		InputStream inputStream = null ;
		try {
			inputStream = new FileInputStream(filePath) ;
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		/**
		 * 判断Excel版本，创建工作簿
		 */
		try {
			if (extension.equals(".xls")) {
				workbook=new HSSFWorkbook(inputStream);
			} else if (extension.equals(".xlsx")){
				workbook=new XSSFWorkbook(inputStream);
			} 
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		
		//读取工作表
		if (extension.equals(".xls")) {
			if(com.dhcc.DRGsHosp.infra.util.StringUtils.hasLength(sheetName))
			{
				sheet=(HSSFSheet) workbook.getSheet(sheetName);
			}
			else {
				sheet=(HSSFSheet) workbook.getSheetAt(index);
			}
			
		} else if(extension.equals(".xlsx")){
			if(com.dhcc.DRGsHosp.infra.util.StringUtils.hasLength(sheetName))
			{
				sheet=(XSSFSheet) workbook.getSheet(sheetName);
			}
			else {
				sheet=(XSSFSheet) workbook.getSheetAt(index);
			}
		} 
		return sheet;
	}
	/**
	 * 
	 *  @Description：获取进度
	 *  @Author LiuHongJun  
	 *  @see com.dhcc.DRGsHosp.facade.BenchmarkFileUploadFacade#uploadProgress()
	 */
	@Override
	public InvokeResult uploadProgress() {
		/**
         * fileInfo-正在处理的文件
         * saveInfo-保存信息
         * dataInfo-数据信息
         * errorInfo-错误信息
         * stateInfo-状态
         * percent-百分比
         */
		DecimalFormat df = new DecimalFormat("##0.00");
		Map<String,Object> map=new HashMap<>();
//		if(stateInfo=="1") {
//			message.setLength(0);
//			message.append("解析文件完毕")  ;	
//		}
		map.put("msg", message);
		map.put("stateInfo", stateInfo);
		map.put("percent", df.format(percent.floatValue()));
		map.put("detail", detail);
		map.put("time", time);
		return InvokeResult.success(map);
	}
	 
	/**
	 * @methodname    :printProgress
	 * @description   :打印循环的进度
	 * @param         :total：总数，i：当前位置
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年1月26日
	 */
	private void printProgress(int total,int i) {
		percent=(float)i*100/(float)total;
		if(i>=total)
		{percent=100f;}
		long perTime = (new Date().getTime()-mdStartTime)/i;//平均时间
		time = ms2desc((total-i)*perTime);//剩余时间
	}
	/**
	 * @methodname    :ms2desc
	 * @description   :毫秒转时间描述
	 * @param         :
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年5月29日
	 */
	public static String ms2desc(long ms){
		long hour=ms/(1000*60*60);
		long minute=(ms%(1000*60*60))/(1000*60);
		long second=(ms%(1000*60))/(1000);
		String desc = "";
		if (hour>0) {
			desc+=hour+"小时";
		}
		if (minute>0) {
			desc+=minute+"分";
		}
		
		if (second>0) {
			desc+=second+"秒";
		}
		return desc;
	}
}
